<template>
  <div class="treeBox">
    <ul v-show="contextMenuVisible" class="contextmenu" :style="{ left: left + 'px', top: top + 'px' }">
      <li @click="curTabReload()">编辑</li>
    </ul>
    <el-autocomplete v-model="filterText" :fetch-suggestions="querySearch" clearable
      class="inline-input w-50 filterText" :trigger-on-focus="false" :placeholder="i18n.fy.enterprojectname"
      @select="handleSelect" :prefix-icon="Search" />
    <el-tree v-if="spinning" ref="treeRef" :filter-node-method="filterNode" node-key="id" :data="data"
      :highlight-current='true' :props="defaultProps" @node-click="handleNodeClick" :default-expand-all="expand"
      :default-expanded-keys="[1, 21]" :class="{ 'electricityFlag': !electricityFlag }">
      <template #default="{ node, data }">
        <span @contextmenu.prevent.stop="rightClick(data, $event)" :class="{ 'nodeTest': data.children.length == 0 }">
          <span>
            <el-icon v-if="node.expanded">
              <Box v-if='node.level < 3 && !electricityFlag' style="color: yellow;position: relative;
               top: -3px;" />
              <Coin style="color: yellow;position: relative;
               top: -3px;" v-show="node.level >= 3 && !electricityFlag" />
              <i v-if='node.level != 4' v-show="electricityFlag"
                class="dtreefont dtree-icon-wenjianjiazhankai dtreefont-special dtree-theme-dtreefont dtree-theme-icon"
                data-spread="open" data-id="53" dtree-id="deviceTree" data-iconclass=""
                style="position: relative;left: -3px;"></i>
            </el-icon>
            <el-icon v-else>
              <Box v-if='node.level < 3 && !electricityFlag' style="color: yellow;position: relative;
               top: -3px;" />
              <Coin style="color: yellow;position: relative;top: -3px;" v-if="node.level >= 3 && !electricityFlag" />
              <i v-if="electricityFlag && data.children.length > 0"
                class="dtreefont-special dtree-theme-dtreefont dtree-theme-icon dtreefont dtree-icon-weibiaoti5"
                data-spread="close" data-id="53" dtree-id="deviceTree" data-iconclass=""
                style="position: relative;left: -3px;"></i>
            </el-icon>
            <el-icon v-if="data.children.length == 0">
              <Coin style="color: yellow;position: relative;top: 2px;" v-if="!electricityFlag" />
              <i v-else class="dtreefont dtreefont-special dtree-theme-dtreefont dtree-theme-icon"
                :class="data.iconClass" data-spread="last" dtree-id="deviceTree" data-iconclass=""></i>
            </el-icon>
            <span :title="node.label" :class="'gatewayType' + data.gatewayType">{{ node.label }}</span>
          </span>
        </span>
      </template>
    </el-tree>
    <!-- 新增和修改的弹出层开始 -->
    <div style="display: none;padding: 20px;text-align: center;z-index:15!important" class="bgimg saveOrUpdateDivbs"
      id="saveOrUpdateDiv3">
      <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
        <input type="hidden" name="fid" value="1">
        <input type="hidden" name="type" value="0">
        <div class="layui-form-item">
          <div class="layui-input-block" style=" padding: 4px 0;">
            <label class="layui-form-label">设备昵称:</label>
            <div class="layui-input-inline">
              <input type="hidden" name="id">
              <input type="text" name="nickName" lay-verify1="required" placeholder="请输入设备名称" autocomplete="off"
                class="layui-input txt" id="nickName">
            </div>
          </div>
          <div class="layui-inline" style="visibility: hidden;    display: none;">
            <label class="layui-form-label">设备Key:</label>
            <div class="layui-input-inline">
              <input type="text" name="accessKey" lay-verify1="required" placeholder="请输入设备Key" autocomplete="off"
                class="layui-input txt">
            </div>
          </div>
        </div>
        <div class="layui-form-item" style="margin-bottom:2px;">
          <div class="layui-input-block">
            <label class="layui-form-label">网关类型:</label>
            <div class="layui-input-block">
              <input type="radio" name="gatewayType" value="1" title="无线" checked="checked">
              <input type="radio" name="gatewayType" value="0" title="有线">
            </div>
          </div>
        </div>
        <div v-show="false" class="layui-form-item">
          <div class="layui-input-block">
            <div class="layui-input-block">
              <input type="text" name="deviceName" placeholder="请输入用户码" autocomplete="off" class="layui-input txt">
            </div>
          </div>
        </div>
        <div v-show="false" class="layui-form-item">
          <div class="layui-input-block">
            <div class="layui-input-block">
              <input type="text" name="productKey" placeholder="productKey" autocomplete="off" class="layui-input txt">
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <label class="layui-form-label">区:</label>
            <div class="layui-input-inline">
              <el-select multiple v-model="district" :placeholder="i18n.language === 'zh-cn' ? '区' : 'distinguish'">
                <el-option v-for="item in deviceAreaAllList" :value="item.area_code_lable">
                  {{ item.area_code_lable }}
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <label class="layui-form-label">组:</label>
            <div class="layui-input-inline">
              <el-select v-model="group" multiple placeholder="">
                <el-option v-for="item in options" :value="item.group_name_label">{{ item.group_name_label }}
                </el-option>
              </el-select>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <label class="layui-form-label">用户码:</label>
            <div class="layui-input-inline">
              <input type="text" name="simId" placeholder="请输入用户码" autocomplete="off" class="layui-input txt">
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <div class="layui-input-block">
            <label class="layui-form-label">部署类型:</label>
            <div class="layui-input-inline">
              <input type="radio" name="isPrivate" value="1" title="私有" checked="checked">
              <input type="radio" name="isPrivate" value="0" title="公有">
            </div>
          </div>
        </div>
        <div class="layui-form-item" style="text-align: center;">
          <div class="layui-input-block" style="text-align: center;margin-left: 0px;">
            <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release"
              lay-filter="doSubmit" lay-submit="">
              {{ i18n.language === 'zh-cn' ? '提交' : 'submit' }}
            </button>
            <button type="button" @click="refresh"
              class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
              {{ i18n.language === 'zh-cn' ? '重置' : 'resetting' }}
            </button>
          </div>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { Search } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();
import { wirelessManageStore } from "@/pinia/wirelessManage";
import { getProjectTree } from '@/api/projectApi'
const wmStore = wirelessManageStore();

const { appContext: { config: { globalProperties } } } = getCurrentInstance()
let $httpUrl = globalProperties.$httpUrl;

let filterText = ref('');
let props = defineProps({
  gatewayType: {
    type: Number,
    default: ''
  }
})
watch(filterText, (val) => {
  treeRef.value.filter(val)
})
let emit = defineEmits(['query'])
const formatToTree = (ary, pid, pidName = 'parentId') => {
  return ary
    .filter((item) => item[pidName] === pid)
    .map((item) => {
      // 通过父节点ID查询所有子节点
      item.children = formatToTree(ary, item.id);
      return item;
    });
}

let oldVal = [];
let mainIndex = '';
let url = $httpUrl + "/device/addDevice";

function isValidString (input) {
  let length = input.length;
  let extraLength = 0;

  // 计算中文和日文字符数量
  let match = input.match(/[^\u0000-\u00ff]/g); // 匹配非单字节字符（包括中文和日文）
  if (match) {
    extraLength = match.length;
  }

  // 计算实际长度（中文和日文算2个字符）
  let actualLength = length + extraLength;

  // 长度检查
  if (actualLength < 4 || actualLength > 64) {
    return false;
  }

  // 正则表达式检查
  return /^[a-zA-Z0-9_\u4E00-\u9FA5\u3040-\u30FF]+$/.test(input);
}

const edit = (row) => { // 编辑
  url = $httpUrl + '/device/updateDevice';
  mainIndex = layer.open({
    type: 1,
    title: '修改设备昵称',
    content: $("#saveOrUpdateDiv3"),
    area: ['700px', '50%'],
    maxmin: true,
    success: function (index) {
      layui.use(['form'], () => {
        let form = layui.form
        form.val("dataFrm", JSON.parse(JSON.stringify(row)));
        form.render();
        //保存
        form.on("submit(doSubmit)", function (obj) {
          if ($("#nickName").val() == '') {
            layer.msg("设备昵称不能为空");
            return false;
          }
          if (!isValidString($("#nickName").val())) {
            layer.msg("设备昵称不合法！ 只中文、英文字母、日文、数字和下划线（_），长度限制为 4 ~ 64 个字符，中文及日文算 2 个字符");
            return false;
          }
          //序列化表单数据
          var params = $("#dataFrm").serialize();
          let json_data = JSON.parse(formToJson(params));
          json_data.nickName = decodeURI(json_data.nickName);
          let groupNumberList = [];
          let areaNumberList = [];
          for (let i = 0; i < group.value.length; i++) {
            let item = group.value[i];
            for (let j = 0; j < options.value.length; j++) {
              if (item == options.value[j].group_name_label) {
                groupNumberList.push(options.value[j].group_name);
                break;
              }
            }
          }
          json_data.groupNumber = groupNumberList.toString();
          for (let i = 0; i < district.value.length; i++) {
            let item = district.value[i];
            for (let j = 0; j < deviceAreaAllList.value.length; j++) {
              if (item == deviceAreaAllList.value[j].area_code_lable) {
                areaNumberList.push(deviceAreaAllList.value[j].area_code);
                break;
              }
            }
          }
          json_data.areaNumber = areaNumberList.toString();
          $axios.post('/device/updateDevice', json_data).then(res => {
            if (res.data.message == "成功") {
              obj = "保存成功"
            }
            layer.msg(obj);
            //关闭弹出层
            layer.close(mainIndex)
          }).catch(err => { })
        });
      })
    }
  });
}




const formToJson = (data) => {
  data = data.replace(/&/g, "\",\"");
  data = data.replace(/=/g, "\":\"");
  data = "{\"" + data + "\"}";
  return data;
}
let curData = {};
const curTabReload = () => {
  edit(curData);
}
let left = ref();
let top = ref();
let pid = ref();
const rightClick = (item, e) => {
  console.log('rightClick->', item, e);
  if (item.children.length != 0) {
    return false;
  }
  let str = window.location.href;
  if (str.includes('toUserOperation') || str.includes('toWarningManager') || str.includes('toDeviceTimingRuleManager')) {
    return false;
  }
  e.preventDefault(); //防止默认菜单弹出
  contextMenuVisible.value = true;
  left.value = e.pageX;
  top.value = e.pageY + 10;
  let obj = {
    deviceFid: item.id
  }
  pid.value = item.id;
  $axios.post('/device/getDeviceInfo', obj).then(res => {
    if (res.data.data.simId == null) {
      res.data.data.simId = '';
    }
    res.data.data.simId = decodeURI(res.data.data.simId);
    curData = res.data.data;
    if (curData.areaNumber == null || curData.areaNumber == '') {
      district.value = []
    } else {
      let arr = curData.areaNumber.split(',');
      let obj = [];
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].length > 3 && arr[i].includes(' ')) {
          obj.push(arr[i])
        } else {
          obj.push(arr[i]);
        }
      }
      district.value = obj;
    }
    if (curData.groupNumber == null || curData.groupNumber == '') {
      group.value = []
    } else {

      let arr2 = curData.groupNumber.split(',');
      let obj2 = [];
      for (let i = 0; i < arr2.length; i++) {
        if (arr2[i].length > 3 && arr2[i].includes(' ')) {
          obj2.push(arr2[i])
        } else {
          obj2.push(arr2[i]);
        }
      }
      group.value = obj2;
    }
    getDeviceAliasAllList()
    getDeviceAreaAllList();
  })
  data.loading = false;
}

const treeRef = ref();
const filterNode = (value, data1) => {
  console.log('tree->filterNode', value);
  if (!value) {
    let arr = JSON.parse(JSON.stringify(oldVal));
    for (let i = arr.length - 1; i >= 0; i--) {
      for (let j = arr[i].children.length - 1; j >= 0; j--) {
        for (let m = arr[i].children[j].children.length - 1; m >= 0; m--) {
          if (arr[i].children[j].children[m].children.length == 0) {
            arr[i].children[j].children.splice(m, 1);
          }
        }
      }
    }
    data.value = arr;
    return true
  }

  let arr = JSON.parse(JSON.stringify(oldVal));
  for (let i = arr.length - 1; i >= 0; i--) {
    for (let j = arr[i].children.length - 1; j >= 0; j--) {
      for (let m = arr[i].children[j].children.length - 1; m >= 0; m--) {
        if (!arr[i].children[j].children[m].nickName.includes(value)) {
          arr[i].children[j].children.splice(m, 1);
        }
      }
    }
  }
  data.value = arr;
}
let spinning = ref(false);
let expand = ref(null);

const getList = async (gatewayType) => {
  if (gatewayType == undefined) {
    return;
  }
  var formData = new FormData(); // 当前为空
  data.loading = true;
  if (gatewayType < 2) {
    formData.append('gatewayType', gatewayType);
  } else {
    formData = new FormData(); // 当前为空
  }

  $axios.post('/device/initUserDeviceLeftTreeJson', formData).then(res => {
    console.log('获取产品树(老)->', res.data);
    res.data.data.map((item) => {
      if (item.deviceStatus == 'OFFLINE' || item.deviceStatus == "UNACTIVE") {
        item.iconClass = 'dtree-icon-shuye1 OFFLINE';
      } else if (item.deviceStatus == 'ONLINE') {
        item.iconClass = 'dtree-icon-shuye1 ONLINE';
      }
      item.children = [];
    })
    let arr = [];
    for (let i = 0; i < res.data.data.length; i++) {
      if (res.data.data[i].type == 1) {
        res.data.data[i].nickName = res.data.data[i].productName;
        arr.push(res.data.data[i]);
      }
    }
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < res.data.data.length; j++) {
        if (arr[i].id == res.data.data[j].fid) {
          arr[i].children.push(res.data.data[j]);
        }
      }

    }
    let obj = [{
      "id": 1,
      "menuId": null,
      "nickName": "系统信息",
      "iconClass": "",
      "href": null,
      "spread": true,
      "target": null,
      "gatewayType": 0,
      "children": [
        {
          "id": 21,
          "menuId": null,
          "nickName": "智慧照明平台",
          "iconClass": "",
          "href": null,
          "spread": true,
          "target": null,
          "gatewayType": 0,
          "children": arr,
          "checkArr": "0",
          "parentId": 1
        }
      ],
      "checkArr": "0",
      "parentId": 0
    }]


    data.value = obj;
    oldVal = JSON.parse(JSON.stringify(obj));
    for (let i = data.value.length - 1; i >= 0; i--) {
      for (let j = data.value[i].children.length - 1; j >= 0; j--) {
        for (let m = data.value[i].children[j].children.length - 1; m >= 0; m--) {
          restaurants.value.push(
            { value: data.value[i].children[j].children[m].nickName, link: '' },
          )
          if (data.value[i].children[j].children[m].children.length == 0 && electricityFlag.value) {
            data.value[i].children[j].children.splice(m, 1);
          }
        }
      }
    }
    expand.value = data.value[0].children[0].children.length < 8 ? true : false;
    spinning.value = true;
  })
  data.loading = false;
}
const handleNodeClick = (row) => {
  if (row.type) {
    if (row.type === 1) {
      console.log('row->', row);
      wmStore.setTreeProject({ productId: row.id, productName: row.productName })
    } else {
      wmStore.setTreeProject({ productId: row.fid, productName: '' })
      wmStore.setTreeGateway({ gatewayId: row.id, gatewayName: row.nickName })
    }
  }
  let parentId = row.parentId;
  let obj = oldVal[0].children[0].children.filter((item) => {
    return item.id == row.fid;
  })

  let arr = obj[0] && obj[0].children;
  /// //console.log(oldVal);
  let id = row.id;
  let query = {}
  if (row.gatewayType == 1) {
    query = { deviceFid: id, gatewayType: row.gatewayType }
  } else {
    query = { deviceFid: id }
  }

  emit('query', query)
  emit('gateway', arr)
  //console.log(arr)
}


const refresh = () => {
  $(".saveOrUpdateDivbs  input.txt").val('');
  district.value = '';
  group.value = '';
}




const uniqueFunc = (arr, uniId) => {
  const res = new Map();
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}

let options = ref([]);
let group = ref([]);
const getDeviceAliasAllList = () => {
  if (!pid.value) {
    return;
  }
  $.post($httpUrl + "/operationDevice/deviceGroupAllList", {
    deviceFid: pid.value
  }, function (res) {
    // options.value=res.data;
    res.data.map((item) => {
      item.v = item.group_name;
      if (item.group_name.length > 3 && item.group_name.includes(' ')) {
        item.group_name_label = item.group_name;
      } else {
        item.group_name_label = item.group_name;
      }
    });
    let newArr = uniqueFunc(res.data, "group_name");
    newArr = newArr.sort(createComprisonFunction('group_name_label'))


    options.value = newArr;
    // options.value.unshift({
    //   group_name: "全部",
    //   name: '全部',
    //   v: "全部"
    // })
  })
}

let deviceAreaAllList = ref([]);
let district = ref([]);
const getDeviceAreaAllList = () => {

  var formData = new FormData(); // 当前为空
  formData.append('deviceFid', pid.value);
  $axios.post('/operationDevice/deviceAreaAllList', formData).then(res => {
    // deviceAreaAllList.value=res.data.data;
    res.data.data.map((item) => {
      // if (item.area_code.length == 1) {
      //   item.area_code = '00 0' + item.area_code;
      // }
    })
    let newArr = arrDistinctByProp(res.data.data, 'area_code');
    newArr.map((item) => {
      item.area_code_lable = item.area_code;
    })
    newArr = newArr.sort(createComprisonFunction('area_code_lable'))
    deviceAreaAllList.value = newArr;
  }).catch(err => {

  })

}

const arrDistinctByProp = (arr, prop) => {
  let obj = {};
  return arr.reduce(function (preValue, item) {
    obj[item[prop]] ? '' : obj[item[prop]] = true && preValue.push(item);
    return preValue
  }, [])
}

const hex2int = (hex) => {
  if (hex == null || hex == '') {
    return;
  }
  if (hex == null || hex == '') {
    return;
  }
  var len = hex.length, a = new Array(len), code;
  for (var i = 0; i < len; i++) {
    code = hex.charCodeAt(i);
    if (48 <= code && code < 58) {
      code -= 48;
    } else {
      code = (code & 0xdf) - 65 + 10;
    }
    a[i] = code;
  }

  return a.reduce(function (acc, c) {
    acc = 16 * acc + c;
    return acc;
  }, 0);
}



const createComprisonFunction = (propertyName) => {
  return function (object1, object2) {
    var value1 = object1[propertyName];
    var value2 = object2[propertyName];
    if (value1 < value2) {
      return -1;
    } else if (value1 > value2) {
      return 1;
    } else {
      return 0;
    }
  }
}

const restaurants = ref([]);
const handleSelect = (item) => {
}
const querySearch = (queryString, cb) => {

  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value
  cb(results)
}
const createFilter = (queryString) => {
  return (restaurant) => {
    return (
      restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) > -1
    )
  }
}
const loadAll = () => {
  return [
    { value: 'vue', link: 'https://github.com/vuejs/vue' },
    { value: 'element', link: 'https://github.com/ElemeFE/element' },
    { value: 'cooking', link: 'https://github.com/ElemeFE/cooking' },
    { value: 'mint-ui', link: 'https://github.com/ElemeFE/mint-ui' },
    { value: 'vuex', link: 'https://github.com/vuejs/vuex' },
    { value: 'vue-router', link: 'https://github.com/vuejs/vue-router' },
    { value: 'babel', link: 'https://github.com/babel/babel' },
  ]
}

let data = ref([{ children: [{ children: [] }] }])

const defaultProps = {
  children: 'children',
  label: 'nickName',
}
let contextMenuVisible = ref(false);
let electricityFlag = ref(true)
onBeforeMount(() => {
  electricityFlag.value = !window.location.href.includes('electricityList')
  getList(props.gatewayType);
  $("body").click(function () {
    contextMenuVisible.value = false;
  })
})
</script>

<style lang="scss" scoped>
.gatewayType1 {
  color: deepskyblue;
}

.treeBox {
  background-color: #212121;
  height: 100%;
  margin: 0.5rem;

  .el-tree {
    overflow: scroll;
    height: 100%;
  }

  .el-icon {
    height: auto;
    width: auto;
    line-height: normal;
  }
}

:deep(.el-tree-node__expand-icon.expanded) {
  display: none;
}

:deep(.el-tree-node__expand-icon) {
  display: none;
}

:deep(.el-icon:empty) {
  display: none;
}

.gatewayType0 {
  overflow: hidden;
  width: 115px;
  display: inline-block;
  overflow: hidden; // 溢出隐藏
  text-overflow: ellipsis; // 溢出用省略号显示
  white-space: nowrap; // 规定段落中的文本不进行换行
}

.saveOrUpdateDivbs .layui-input-block {
  overflow: hidden;
  text-align: left;
  padding: 0px 0;

}

.saveOrUpdateDivbs .layui-input-block .layui-form-label {
  margin-left: 85px;
}

.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 8px 0;
  border-radius: 2px;
  font-size: 12px;
  font-weight: 400;
  color: #33363c;
  -webkit-box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .15);
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, .15);
}

.contextmenu li {
  margin: 0;
  padding: 0 17px;
  cursor: pointer;
  font-size: 12px;
  line-height: 22px;
  height: 22px;
  border-radius: 2px;
  font-size: 14px;
}

.contextmenu li:hover {
  background: #f2f2f2;
}

.contextSpan {
  height: 100%;
  display: inline-block;
  padding: 0 5px;
  padding-left: 8px;
}

.nodeTest {
  display: block;
  width: 125px;
  height: 32px;
  line-height: 32px;

  .gatewayType0 {
    vertical-align: middle;
  }
}

:deep(.saveOrUpdateDivbs .el-input__wrapper) {
  background: none;
}

:deep(.saveOrUpdateDivbs .el-input__inner) {
  color: #fff;
}

:deep(.electricityFlag .el-tree-node__children .el-tree-node__children .el-tree-node__children) {
  display: none !important;
}
</style>
<style>
.layui-layer-page {
  z-index: 111 !important;
}

.layui-layer-shade {
  z-index: 11 !important;
}
</style>
<style>
.filterText .el-input__wrapper {
  background: #383838;
  color: #fff !important;
  margin-bottom: 0.5rem;
  padding: 0.2rem 0.8rem;
}

.filterText input {
  background: none !important;
  color: #fff !important;
}

.filterText input::placeholder {
  font-size: 14px;
}
</style>
